package com.guang.springbootselfmvc.controlleradvice;

import com.guang.springbootselfmvc.exception.ServiceException;
import com.guang.springbootselfmvc.exception.ServiceExceptions;
import com.guang.springbootselfmvc.restful.IgwHttpEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class ExceptionControllerAdvice {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionControllerAdvice.class);

    public ExceptionControllerAdvice() {
    }

    @ExceptionHandler({Throwable.class})
    // 设置响应的response的响应码状态
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public IgwHttpEntity<Object> buildErrorMessage(Throwable t) {
        if (t instanceof ServiceException) {
            ServiceException serviceException = (ServiceException)t;
            return IgwHttpEntity.buildFailResponse(serviceException);
        } else {
            logger.error("未捕获异常", t);
            return IgwHttpEntity.buildFailResponse(ServiceExceptions.F999.buildServiceException());
        }
    }
}